<template>
  <div class="pro-dialog-form">
    <n-modal
      v-model:show="show"
      v-bind="modalProps"
      preset="dialog"
      title="Dialog"
    >
      <template #header>
        <slot name="header" />
      </template>
      <pro-form
        v-bind="$attrs"
        ref="proFormRef"
        :form="form"
        @formItemChange="handleChange"
      >
      </pro-form>
      <template #action>
        <slot name="action">
          <n-button
            @click="handleReset"
            :disabled="loading"
            style="margin: 10px 10px"
          >
            重置
          </n-button>
          <n-button
            @click="handleSubmit"
            :loading="loading"
            style="margin: 10px 0"
          >
            提交
          </n-button>
        </slot>
      </template>
    </n-modal>
  </div>
</template>

<script lang="ts" setup name="proDialogForm">
  const props = defineProps({
    showModal: {
      type: Boolean,
      default: false
    },
    form: {
      type: Object,
      default: () => ({})
    },
    loading: {
      type: Boolean,
      default: false
    },
    modalProps: {
      type: Object,
      default: () => ({})
    }
  })
  const { showModal } = toRefs(props)
  const show = ref(true)
  const emits = defineEmits(['formItemChange'])
  defineExpose({
    handleValidate,
    handleReset,
    handleChange,
    handleSubmit,
    validateByYourSelf
  })
  const proFormRef = ref()
  /**
   * @description: 表单验证
   * @return {*}
   */
  function handleValidate() {
    proFormRef.value && proFormRef.value.validate()
  }
  /**
   * @description: 重置表单
   * @return {*}
   */
  function handleReset() {
    proFormRef.value && proFormRef.value.handleReset()
  }
  /**
   * @description: form数据改变
   * @param {array} args
   * @return {*}
   */
  function handleChange(...args) {
    emits('formItemChange', ...args)
  }
  /**
   * @description: 处理form提交
   * @return {*}
   */
  function handleSubmit() {
    proFormRef.value && proFormRef.value.handleSubmit()
  }
  /**
   * @description: 自定义验证加强
   * @param {*} func 函数
   * @return {*}
   */
  function validateByYourSelf(func: any) {
    proFormRef.value && proFormRef.value.validateByYourSelf(func)
  }
  watch(show, (val) => {
    if (val !== showModal.value) emits('update:showModal', val)
  })
  watch(showModal, (val) => {
    if (val !== show.value) show.value = val
  })
</script>

<style lang="less" scoped></style>
